<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统</title>

    <style>
        /* 进度条样式 */
        #progress-container {
            height: 20px;
            width: 30%;
            background-color: #f3f3f3;
            border: 1px solid #ccc;
            margin-top: 1px;
            margin-left: 20px;
        }

        .wifi-list-container {
            max-height: 200px; /* 限制WiFi列表的最大高度 */
            overflow-y: auto;  /* 启用垂直滚动条 */
            border: 1px solid #ccc; /* 可选：为容器添加边框以便更好地观察效果 */
            -webkit-overflow-scrolling: touch;
        }
        .wifi-list {
            list-style-type: none;
            padding: 0;
        }
        .wifi-list li {
            padding: 10px;
            cursor: pointer;
        }
        .wifi-list li:hover {
            background-color: #f0f0f0;
        }
        .selected {
            background-color: #d4edda;
            color: #155724;
        }
    </style>
</head>
<body style="width: 62%; margin: 0 auto;">
    <h1 style="text-align: center;">WiFi Configure</h1>
    <br>

    <br>
    <label for="wifiName">WiFi 名称:</label>
    <input type="text" id="wifiName" placeholder="输入WiFi名称">
    <label for="wifiPassword">密码:</label>
    <input type="text" id="wifiPassword" placeholder="输入WiFi密码">
    <button onclick="setWifi()">设定</button>
    <button onclick="scanWifi()">扫描WiFi</button>
    <label id="wifi-indicator"></label>
    <br><br>
    <div class="wifi-list-container">
        <ul id="wifiList" class="wifi-list"></ul>
    </div>
    <script>
        function clearWifiIndicator() {
            document.getElementById('wifi-indicator').innerText = '';
        }

        let wifiList = []; // 存储模拟的WiFi列表

        function scanWifi() {
            
            document.getElementById('wifi-indicator').innerText = '正在扫描WiFi...';
            document.getElementById('wifi-indicator').style.backgroundColor = '#4caf50';

            wifiList = [];

            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/scanWifi', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }
                    
                    /* Start: 去重 */
                    var raw = JSON.parse(response);
                    for (var i = 0; i < raw.length; i++) {
                        var isDup = false;
                        for (var j = 0; j  < wifiList.length; j++) {
                            if (raw[i] === wifiList[j]) {
                                isDup = true;
                            }
                        }
                        if (!isDup) { 
                            wifiList.push(raw[i]);
                        }
                    }
                    /* End: 去重 */
                    updateWifiList();
                    document.getElementById('wifiName').value = wifiList[0];
                    document.getElementById('wifiPassword').value = "";

                    document.getElementById('wifi-indicator').innerText = '扫描完成';
                    setTimeout(clearWifiIndicator, 2000);
                }
            };

            xhr.send();
        }

        function updateWifiList() {
            const wifiUl = document.getElementById('wifiList');
            wifiUl.innerHTML = ''; // 清空现有列表

            wifiList.forEach(function(wifiName) {
                const listItem = document.createElement('li');
                listItem.textContent = wifiName;
                listItem.addEventListener('click', function() {
                    fillWifiName(wifiName);
                });
                wifiUl.appendChild(listItem);
            });
        }

        function fillWifiName(wifiName) {
            document.getElementById('wifiName').value = wifiName;
        }

        function setWifi() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/setWifi', true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById('wifi-indicator').innerText = '成功';
                    document.getElementById('wifi-indicator').style.backgroundColor = '#4caf50';
                    setTimeout(clearWifiIndicator, 2000);
                } else {
                    document.getElementById('wifi-indicator').innerText = '失败';
                    document.getElementById('wifi-indicator').style.backgroundColor = '#f44336';
                    setTimeout(clearWifiIndicator, 2000);
                }
            }

            var wifiArgs = {};
            wifiArgs.ssid = document.getElementById('wifiName').value;
            wifiArgs.password = document.getElementById('wifiPassword').value;

            xhr.send(JSON.stringify(wifiArgs, null, 2));
        }

    </script>
    <br><br>
    <hr>

    温度：<label id="temperature">Loading...</label>℃<br>
    湿度：<label id="humidity">Loading...</label>%<br>
    时间：<label id="time-RTC">Loading...</label>
    &nbsp;&nbsp;&nbsp;<button onclick="setRTC()">同步浏览器时间</button>
    <script>
        function refreshTemperature() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/temperature', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }

                    var raw = JSON.parse(response);
                    document.getElementById('temperature').innerText = raw.temperature;
                    document.getElementById('humidity').innerText = raw.humidity;
                    setTimeout(clearWifiIndicator, 2000);
                }
            };

            xhr.send();
        }
        refreshTemperature();
        setInterval(refreshTemperature, 15000);

        function refreshTimeRTC() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/time-RTC', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }

                    let date = new Date((response - 3600*8)*1000);
                    // 使用Date对象的各种方法来格式化日期和时间
                    let year = date.getFullYear();
                    let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数，所以需要加1
                    let day = String(date.getDate()).padStart(2, '0');
                    let hours = String(date.getHours()).padStart(2, '0');
                    let minutes = String(date.getMinutes()).padStart(2, '0');
                    // let seconds = String(date.getSeconds()).padStart(2, '0');
                    // 拼接成日期时间字符串
                    // let formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    let formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}`;

                    document.getElementById('time-RTC').innerText = formattedDateTime;
                }
            };

            xhr.send();
        }
        refreshTimeRTC();
        setInterval(refreshTimeRTC, 10000);

        function setRTC() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/setRTC', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            let now = new Date().getTime() / 1000;
            xhr.send(parseInt(now) + 8*3600);
        }
    </script>

    <br><br><br>
        <label>蜂鸣 ：</label>
        <input type="radio" id="buz-on" name="buz" value="1" onclick="relay(0, true)">
        <label for="buz-on">接通</label>
        <input type="radio" id="buz-off" name="buz" value="0" onclick="relay(0, false)">
        <label for="buz-off">断开</label>
        <input type="range" min="0" max="30" value="15" step="1" id="volume-slider" onchange="setVolume()">
        <br><br>
        <label>通道1：</label>
        <input type="radio" id="ch1-on" name="ch1" value="1" onclick="relay(1, true)">
        <label for="ch1-on">接通</label>
        <input type="radio" id="ch1-off" name="ch1" value="0" onclick="relay(1, false)">
        <label for="ch1-off">断开</label>
        <br><br>
        <label>通道2：</label>
        <input type="radio" id="ch2-on" name="ch2" value="on" onclick="relay(2, true)"">
        <label for="ch2-on">接通</label>
        <input type="radio" id="ch2-off" name="ch2" value="off" onclick="relay(2, false)">
        <label for="ch2-off">断开</label>
        <br><br>
        <label>LED：</label>
        <input type="radio" id="led-on" name="led" value="on" onclick="relay(3, true)"">
        <label for="led-on">接通</label>
        <input type="radio" id="led-off" name="led" value="off" onclick="relay(3, false)">
        <label for="led-off">断开</label>
        <input type="range" min="0" max="100" value="50" step="1" id="brightness-slider" onchange="setBrightness()">
    <script>
        function relay(channel, connect) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/relay', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            var args = {};
            args.channel = channel;
            args.connect = connect;
            xhr.send(JSON.stringify(args, null, 2));
        }

        function setBrightness() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/setBrightness', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            var args = document.getElementById('brightness-slider').value;
            xhr.send(args);
        }

        function getBrightness() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/getBrightness', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }

                    document.getElementById('brightness-slider').value = response;
                }
            };

            xhr.send();
        }
        getBrightness();

        function setVolume() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/setVolume', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            var args = document.getElementById('volume-slider').value;
            xhr.send(args);
        }

        function getVolume() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/getVolume', true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }

                    document.getElementById('volume-slider').value = response;
                }
            };

            xhr.send();
        }
        getVolume();

    </script>
    <br><br><br>

    <button id="save-event" onclick="saveEvent()">保存设置</button>
    <label id="save-indicator"></label>
    <button id="set-auto-ctrl" onclick="setAutoCtrl()">自动控制</button>
    <script>
        function clearSaveIndicator() {
            document.getElementById('save-indicator').innerText = '';
        }

        function saveEvent() {
            var configs = {};

            /* Start: 绝对时间事件 */
            const abstimeContainers = document.querySelectorAll('div.abstime-container');
            var absTimer = [];
            abstimeContainers.forEach(abs => {
                const timePicker = abs.querySelector('input[type="time"]');
                if (timePicker.value) {
                    const operation = abs.querySelector('select[id="operation"]');
                    const channel = abs.querySelector('select[id="channel"]');
                    const repeats = abs.querySelectorAll('input.repeat');

                    var absItem = {};
                    absItem.time = timePicker.value;
                    absItem.operation = Number(operation.value);
                    absItem.channel = Number(channel.value);
                    repeats.forEach(rep => {
                        absItem[rep.value] = rep.checked;
                    });
                    absTimer.push(absItem);
                }
            });
            configs.absTimer = absTimer;
            /* End: 绝对时间事件 */

            /* Start: 温度事件 */
            const tempContainers = document.querySelectorAll('div.temp-container');
            var temp = [];
            tempContainers.forEach(tmp => {
                const compare = tmp.querySelector('select[id="compare"]');
                const targetTemp = tmp.querySelector('input[id="target-temp"]');

                if (targetTemp.value) {
                    const compare = tmp.querySelector('select[id="compare"]');
                    const operation = tmp.querySelector('select[id="operation"]');
                    const channel = tmp.querySelector('select[id="channel"]');

                    var tempItem = {};
                    tempItem.compare = Number(compare.value);
                    tempItem.targetTemp = Number(targetTemp.value);
                    tempItem.operation = Number(operation.value);
                    tempItem.channel = Number(channel.value);
                    temp.push(tempItem);
                } 
            });
            configs.temp = temp;
            /* End: 温度事件 */

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/setTimer', true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById('save-indicator').innerText = '成功';
                    document.getElementById('save-indicator').style.backgroundColor = '#4caf50';
                    setTimeout(clearSaveIndicator, 2000);
                } else {
                    document.getElementById('save-indicator').innerText = '失败';
                    document.getElementById('save-indicator').style.backgroundColor = '#f44336';
                    setTimeout(clearSaveIndicator, 2000);
                }
            }

            var cfg = JSON.stringify(configs, null, 2);
            // console.log(cfg);
            xhr.send(cfg);
        }

        function setAutoCtrl() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/setAutoCtrl', true);
            xhr.send(null);
        }
    </script>
    <br><br>

    <div id="abstime-wrapper"></div>
    <button id="add-abstime">添加绝对时间事件</button>
    <script>
        let abstimeCount = 0;
        const abstimeWrapper = document.getElementById('abstime-wrapper');
        let abstimeValues = []; // 用于存储下拉框值的数组

        // 定义包含下拉框和删除按钮的HTML模板字符串
        const abstimeTemplate = (id) => `
            <div class="abstime-container" style="border: 1px solid #00000017; padding: 10px; margin: 10px; border-radius: 5px;">
                <input type="time" id="timePicker" name="timePicker">
                <select id="operation">
                    <option value="1">接通</option>
                    <option value="0">断开</option>
                </select>
                <select id="channel">
                    <option value="0">蜂鸣</option>
                    <option value="1">通道1</option>
                    <option value="2">通道2</option>
                    <option value="3">LED</option>
                </select>
                &nbsp;&nbsp;&nbsp;&nbsp;<button class="remove-abstime">删除</button>
                <br>
                <input class="repeat" type="checkbox" id="sun-${id}" value="sun">
                <label for="sun-${id}">Sun</label>
                <input class="repeat" type="checkbox" id="mon-${id}" value="mon">
                <label for="mon-${id}">Mon</label>
                <input class="repeat" type="checkbox" id="tue-${id}" value="tue">
                <label for="tue-${id}">Tue</label>
                <input class="repeat" type="checkbox" id="wed-${id}" value="wed">
                <label for="wed-${id}">Wed</label>
                <input class="repeat" type="checkbox" id="thu-${id}" value="thu">
                <label for="thu-${id}">Thu</label>
                <input class="repeat" type="checkbox" id="fri-${id}" value="fri">
                <label for="fri-${id}">Fri</label>
                <input class="repeat" type="checkbox" id="sat-${id}" value="sat">
                <label for="sat-${id}">Sat</label>
            </div>
        `;

        // 为dropdownWrapper添加事件委托，处理删除按钮的点击事件
        abstimeWrapper.addEventListener('click', function(event) {
            if (event.target && event.target.classList.contains('remove-abstime')) {
                const container = event.target.closest('.abstime-container');
                // const id = parseInt(container.querySelector('select').id.split('-')[2], 10);
                container.remove();
                // 删除对应位置的dropdownValues元素（可选，取决于你是否希望保持数组长度与下拉框数量一致）
                // abstimeValues.splice(id, 1);
            }
        });

        // 添加下拉框的按钮点击事件
        document.getElementById('add-abstime').addEventListener('click', function() {
            abstimeValues.push(null); // 初始化新下拉框的值为null
            const newAbstimeContainer = document.createElement('div');
            newAbstimeContainer.innerHTML = abstimeTemplate(abstimeCount); // abstimeCount
            abstimeWrapper.appendChild(newAbstimeContainer);
            abstimeCount++;
        });
    </script>

    <br><br><br>
    <div id="temp-wrapper"></div>
    <button id="add-temp">添加温度事件</button>
    <script>
        let tempCount = 0;
        const tempWrapper = document.getElementById('temp-wrapper');
        let tempValues = []; // 用于存储下拉框值的数组

        // 定义包含下拉框和删除按钮的HTML模板字符串
        const tempTemplate = (id) => `
            <div class="temp-container"  style="border: 1px solid #00000017; padding: 10px; margin: 10px; border-radius: 5px;">
                <select id="compare">
                    <option value="0">高于</option>
                    <option value="1">低于</option>
                </select>
                <input type="number" min="-50" max="120" id="target-temp" name="target-temp" style="width: 60px">℃
                <select id="operation">
                    <option value="1">接通</option>
                    <option value="0">断开</option>
                </select>
                <select id="channel">
                    <option value="0">蜂鸣</option>
                    <option value="1">通道1</option>
                    <option value="2">通道2</option>
                    <option value="3">LED</option>
                </select>
                <button class="remove-temp">删除</button>
            </div>
        `;

        // 为tempWrapper添加事件委托，处理删除按钮的点击事件
        tempWrapper.addEventListener('click', function(event) {
            if (event.target && event.target.classList.contains('remove-temp')) {
                const container = event.target.closest('.temp-container');
                const id = parseInt(container.querySelector('select').id.split('-')[2], 10);
                container.remove();
                // 删除对应位置的tempValues元素（可选，取决于你是否希望保持数组长度与下拉框数量一致）
                tempValues.splice(id, 1);
            }
        });

        // 添加下拉框的按钮点击事件
        document.getElementById('add-temp').addEventListener('click', function() {
            tempValues.push(null); // 初始化新下拉框的值为null
            const newTempContainer = document.createElement('div');
            newTempContainer.innerHTML = tempTemplate(tempCount);
            tempWrapper.appendChild(newTempContainer);
            tempCount++;
        });
    </script>

    <script>
        function loadConfigs() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/configs', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }
                    
                    var raw = JSON.parse(response);
                    document.getElementById('wifiName').value = raw.ssid;
                    document.getElementById('wifiPassword').value = raw.password;
                }
            };
            xhr.send();
        }

        function loadTimers() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/timers', true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = xhr.responseText;
                    if (!response) {
                        return;
                    }
                    
                    var raw = JSON.parse(response);
                    var absTimers = raw.absTimer;
                    for (var i = 0; i < absTimers.length; i++) {
                        const newAbstimeContainer = document.createElement('div');
                        newAbstimeContainer.innerHTML = abstimeTemplate(i);

                        const timePicker = newAbstimeContainer.querySelector('input[type="time"]');
                        const operation = newAbstimeContainer.querySelector('select[id="operation"]');
                        const channel = newAbstimeContainer.querySelector('select[id="channel"]');
                        const repeats = newAbstimeContainer.querySelectorAll('input.repeat');

                        timePicker.value = absTimers[i].time;
                        operation.value = absTimers[i].operation;
                        channel.value = absTimers[i].channel;
                        for (var j = 0; j < repeats.length; j++) {
                            repeats[j].checked = absTimers[i][repeats[j].value];
                        }

                        abstimeWrapper.appendChild(newAbstimeContainer);
                    }
                    abstimeCount = absTimers.length;

                    var temps = raw.temp;
                    for (var i = 0; i < temps.length; i++) {
                        const newTempContainer = document.createElement('div');
                        newTempContainer.innerHTML = tempTemplate(i);

                        const targetTemp = newTempContainer.querySelector('input[id="target-temp"]');
                        const compare = newTempContainer.querySelector('select[id="compare"]');
                        const operation = newTempContainer.querySelector('select[id="operation"]');
                        const channel = newTempContainer.querySelector('select[id="channel"]');

                        compare.value = temps[i].compare;
                        targetTemp.value = temps[i].targetTemp;
                        operation.value = temps[i].operation;
                        channel.value = temps[i].channel;

                        tempWrapper.appendChild(newTempContainer);
                    }
                    tempCount = temps.length;
                }
            };
            xhr.send();
        }

        loadConfigs();
        loadTimers();
    </script>


</body>
</html>
